package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.Page;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.CswhObj;
import com.py.credit.entity.GzObj;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.CjGzTableFieldEnum;
import com.py.credit.entity.enums.JlGzTableFieldEnum;
import com.py.credit.service.CswhService;
import com.py.credit.service.GzService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.service.OfficeService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 联合奖惩规则controller
 */
@Controller
@RequestMapping(value = "/gz")
public class GzController {

    private final static String FRONT_TABLE_CJGZ_ID = "cjgz";

    private final static String FRONT_TABLE_JLGZ_ID = "jlgz";

    @Autowired
    private GzService gzService;

    @Autowired
    private CswhService cswhService;

    @Autowired
    private LhjcRemoteBaseService lhjcRemoteBaseService;

    @Autowired
    private OfficeService officeService;

    @Value("${absolutepath}")
    private String absolutepath;

    /**
     * 奖惩规则普通检索
     *
     * @param jclb 奖惩类别：C:惩戒，J:激励
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getOptionalColums.json")
    public RestServiceResult getOptionalColums(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb) {
        if (jclb.equals("C")) {
            return new RestServiceResult(CjGzTableFieldEnum.getOptionalColumns());
        } else {
            return new RestServiceResult(JlGzTableFieldEnum.getOptionalColumns());
        }
    }

    /**
     * 奖惩规则高级检索
     *
     * @param jclb 奖惩类别：C:惩戒，J:激励
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAdvancedConditionColumns.json")
    public RestServiceResult getAdvancedConditionColumns(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb) {
        if (jclb.equals("C")) {
            return new RestServiceResult(CjGzTableFieldEnum.getAdvancedConditionColumns());
        } else {
            return new RestServiceResult(JlGzTableFieldEnum.getAdvancedConditionColumns());
        }
    }

    /**
     * 规则分页列表
     *
     * @param jclb      奖惩类别：C:惩戒，J:激励
     * @param condition 搜索条件
     * @param page      分页条件
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list.json")
    public RestServiceResult getList(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                     @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                                     Page page, HttpServletRequest request) {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        String[] configColumns = null;
        List<String> showColumns = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            SysUser userInfo = user.getData();
            if (null != userInfo) {
                if (jclb.equals("C")) {
                    configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_CJGZ_ID);
                    showColumns = (configColumns == null || configColumns.length == 0)
                            ? CjGzTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
                } else {
                    configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_JLGZ_ID);
                    showColumns = (configColumns == null || configColumns.length == 0)
                            ? JlGzTableFieldEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
                }
            } else {
                ExceptionLogger.error("GzController#getList", "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("GzController#getList", "未获取到当前用户信息！");
        }

        String[] additionalColumns = {"id"};

        List<Map<String, Object>> tableList = gzService.getByConditionForPage(jclb, showColumns,
                additionalColumns, condition, page);

        List<Map<String, Object>> lhbms = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < tableList.size(); i++) {
            Set<String> set = new HashSet<String>();
            int id = (int) tableList.get(i).get("id");
            lhbms = gzService.selectForLhbm(id);
            String lhbm = "";
            for (Map<String, Object> map : lhbms) {
                set.add((String) map.get("deptName"));
            }

            for (String obj : set) {
                lhbm += obj + ",";
            }
            tableList.get(i).put("lhbm", lhbm.substring(0, lhbm.length() - 1));
        }

        return new RestServiceResult(page.getTotalCount(), tableList);
    }

    /**
     * 添加规则
     *
     * @param file       文件
     * @param name       规则名称
     * @param bm         规则编码
     * @param detailName 联合惩戒制度全称
     * @param cfbm       处罚部门
     * @param csIds      措施ids
     * @param bmIds      部门ids
     * @param lyIds      领域ids
     * @param jclb       奖惩类别：C:惩戒，J:激励
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add.json")
    public RestServiceResult add(@RequestParam(value = "file", required = false) MultipartFile file,
                                 @RequestParam(value = "name", defaultValue = "", required = true) String name,
                                 @RequestParam(value = "bm", defaultValue = "", required = true) String bm,
                                 @RequestParam(value = "detailName", defaultValue = "", required = true) String detailName,
                                 @RequestParam(value = "cfbm", defaultValue = "", required = true) String cfbm,
                                 @RequestParam(value = "csIds", defaultValue = "", required = true) String csIds,
                                 @RequestParam(value = "bmIds", defaultValue = "", required = true) String bmIds,
                                 @RequestParam(value = "lyIds", defaultValue = "", required = true) String lyIds,
                                 @RequestParam(value = "jclb", defaultValue = "", required = true) String jclb
    ) {
        int count = gzService.selectSameBmAndName(name, bm);
        if (count > 0) {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "规则名和编码不能重复！");
        }
        if (cfbm.equals("")) {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "请选择发起部门！");
        }
        if (csIds.equals("") || bmIds.equals("") || lyIds.equals("")) {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "请选择联合奖惩部门！");
        }

        gzService.add(file, name, bm, detailName, cfbm, csIds, bmIds, lyIds, jclb, absolutepath);
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS);
    }

    /**
     * 删除规则
     *
     * @param id 规则id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/del.json")
    public RestServiceResult del(@RequestParam(defaultValue = "", required = true, value = "id") String id) {
        gzService.deleteGz(id);
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS);
    }

    /**
     * 发布规则
     *
     * @param ids 规则id(多个id逗号拼接)
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/release.json")
    public RestServiceResult release(@RequestParam(defaultValue = "", required = true, value = "ids") String ids) {
        gzService.modifyGzzt(ids, "Y");
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS);
    }

    /**
     * 撤销规则
     *
     * @param ids 规则id(多个id逗号拼接)
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/revoke.json")
    public RestServiceResult revoke(@RequestParam(defaultValue = "", required = true, value = "ids") String ids) {
        gzService.modifyGzzt(ids, "N");
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS);
    }

    /**
     * 修改规则
     *
     * @param file       文件
     * @param id         规则id
     * @param name       规则名称
     * @param bm         规则编码
     * @param detailName 联合惩戒制度全称
     * @param cfbm       处罚部门
     * @param csIds      措施ids
     * @param bmIds      部门ids
     * @param lyIds      领域ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/modify.json")
    public RestServiceResult modify(@RequestParam(value = "file", required = false) MultipartFile file,
                                    @RequestParam(value = "id", defaultValue = "", required = true) String id,
                                    @RequestParam(value = "name", defaultValue = "", required = true) String name,
                                    @RequestParam(value = "bm", defaultValue = "", required = true) String bm,
                                    @RequestParam(value = "detailName", defaultValue = "", required = true) String detailName,
                                    @RequestParam(value = "cfbm", defaultValue = "", required = true) String cfbm,
                                    @RequestParam(value = "csIds", defaultValue = "", required = true) String csIds,
                                    @RequestParam(value = "bmIds", defaultValue = "", required = true) String bmIds,
                                    @RequestParam(value = "lyIds", defaultValue = "", required = true) String lyIds) {
        int count = gzService.selectOtherSameBmAndName(id, name, bm);
        if (count > 0) {
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "规则名和编码不能重复！");
        }

        gzService.modifyById(id, file, name, bm, detailName, cfbm, csIds, bmIds, lyIds, absolutepath);
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS);
    }

    /**
     * 文件下载
     *
     * @param id       规则id
     * @param request
     * @param response
     */
    @RequestMapping(value = "/download.json")
    @ResponseBody
    public void download(@RequestParam(value = "id", defaultValue = "", required = true) String id,
                         HttpServletRequest request, HttpServletResponse response) {
        gzService.download(id, request, response);
    }

    /**
     * 是否存在文件
     *
     * @param id 规则id
     * @return
     */
    @RequestMapping(value = "/checkDownload.json")
    @ResponseBody
    public RestServiceResult checkDownload(@RequestParam(value = "id", defaultValue = "", required = true) String id) {
        return new RestServiceResult(gzService.checkDownload(id));
    }

    /**
     * Excel统计导出
     *
     * @param response
     * @param name     规则名称
     * @param bm       规则编码
     * @param gzzt     规则状态：Y：已发布，N:未发布
     * @param type     奖惩类别：C:惩戒，J:激励
     */
    @ResponseBody
    @RequestMapping(value = "/exportExcel.xls")
    public void ExcelExport(HttpServletResponse response,
                            @RequestParam(value = "name", defaultValue = "", required = true) String name,
                            @RequestParam(value = "bm", defaultValue = "", required = true) String bm,
                            @RequestParam(value = "gzzt", defaultValue = "", required = true) String gzzt,
                            @RequestParam(value = "type", defaultValue = "", required = true) String type) {
        gzService.excelExport(response, name, bm, gzzt, type);
    }

    /**
     * 查询规则详情
     *
     * @param gzId 规则id
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectGzDetail.json")
    public RestServiceResult selectOneByAjbh(@RequestParam(defaultValue = "", required = true, value = "gzId") String gzId) {
        Map<String, Object> map = new HashMap<>();
        GzObj gzObj = gzService.selectById(gzId);
        List<CswhObj> cswhObjs = cswhService.selectByGzId(gzId);

        String filePath = gzObj.getFilePath();

        if (null != filePath && !filePath.equals("")) {
            filePath = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
            gzObj.setFilePath(filePath);
        }

        map.put("gzObj", gzObj);
        map.put("cswhObjs", cswhObjs);
        return new RestServiceResult(map);
    }

    @ResponseBody
    @RequestMapping(value = "/getLhjcGzNames.do", method = RequestMethod.POST)
    public RestServiceResult<List<String>> getDeptManager(@RequestParam(defaultValue = "", required = true, value = "cfbm") String cfbm,
                                                          @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb) {
        String result = "";
        try {
            result = gzService.getGzNames(officeService.selectTopDeptId(cfbm), jclb);
        } catch (Exception e) {
            ExceptionLogger.error(e);
        }
        return new RestServiceResult(result);
    }

    /**
     * 自定义列表选项
     *
     * @param jclb    奖惩类别：C:惩戒，J:激励
     * @param columns 列表数组
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addShowColunms.json")
    public RestServiceResult<String> addShowColunms(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                                                    @RequestParam(value = "columns", required = true) String[] columns,
                                                    HttpServletRequest request) {

        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                if (jclb.equals("C")) {
                    MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_CJGZ_ID, columns);
                } else {
                    MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_JLGZ_ID, columns);
                }

            } else {

                ExceptionLogger.error("GzController#addShowColunms", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("GzController#addShowColunms", "未获取到当前用户信息！");
        }

        return new RestServiceResult<String>();
    }

    /**
     * 高级检索文件导出
     *
     * @param jclb      奖惩类别：C:惩戒，J:激励
     * @param condition 查询条件
     * @param columnEN  字段名
     * @param page      分页条件
     * @param response
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/export.json")
    public void export(@RequestParam(value = "jclb", defaultValue = "", required = true) String jclb,
                       @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
                       @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
                       HttpServletResponse response) throws IOException {

        page.setLimit(1000);

        List<String> columns = JSONArray.parseArray(columnEN, String.class);

        List<Map<String, Object>> data = gzService.getByConditionForPage(jclb, columns,
                null, condition, page);

        List<OptionalColumn> optionalColumns = null;

        String excelName = "";
        if (jclb.equals("C")) {
            optionalColumns = CjGzTableFieldEnum.getOptionalColumns();
            excelName = "联合惩戒规则";
        } else {
            optionalColumns = JlGzTableFieldEnum.getOptionalColumns();
            excelName = "联合激励规则";
        }

        ExcelUtil.downloadExcel(response, data, excelName, excelName, columns, optionalColumns);
    }
}
